package com.guofen.pojo;


import com.alibaba.fastjson.JSONObject;
import com.guofen.dao.SjckTableListMapper;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.guofen.util.result.Result;
import com.guofen.util.result.ResultGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.*;
import org.springframework.stereotype.Component;

@Component
@EnableScheduling
@EnableAsync
public class SjckGetToken {

    private String token;
    private long startTime;

    @Value("${spring.datasource.driver-class-name}")
    private String driverName;

    @Value("${spring.datasource.url}")
    private String url;

    @Value("${spring.datasource.username}")
    private String username;

    @Value("${spring.datasource.password}")
    private String password;

    @Autowired
    private SjckTableListMapper tableListMapper;


    public void getToken() {
        //String token = null;
        String getTokenPath = "http://api.lfemcp.com/token/get";
        NameValuePair[] getTokenData = {
                new NameValuePair("appKey","cf0c23336d214172acbda45f3e5f9240"),
                new NameValuePair("appSecret","c5f101a6ab2a4a5e9a94d7d2fc9b6a9c"),
                new NameValuePair("account","CanfitIoT")
        };
        // 获取token
        System.out.println("获取token！");
        String jsonObject = getPost(getTokenPath, getTokenData, token).getData().toString();
        startTime = System.currentTimeMillis();
        SjckHistoryListResult sjckHistoryListResult = JSONObject.parseObject(jsonObject, SjckHistoryListResult.class);
        SjckHistoryListToken sjckHistoryListToken = sjckHistoryListResult.getData();
        token = sjckHistoryListToken.getAccess_token();
    }

    @Async
    @Scheduled(fixedRate = 420000)
    public void getHistoryList() throws SQLException {
        System.out.println("进来了！");
        NameValuePair[] historyListData = {
                new NameValuePair("equipId","19146")
        };
        String HistoryListPath = "http://api.lfemcp.com/history/list";

        // 判断一下token
        long endTime =  System.currentTimeMillis();
        if (token == null || ((endTime-startTime)/1000) >= 7200 ) {
            getToken();
        }
        // 使用token得到历史数据.
        String HistoryJSON = getPost(HistoryListPath, historyListData, token).getData().toString();
        System.out.println("获得历史数据！");
        SjckHistoryResult sjckHistoryResult = JSONObject.parseObject(HistoryJSON, SjckHistoryResult.class);
        // 得到了历史数据sjckHistoryListUp（heads，values）之后开始插入到数据库中。
        SjckHistoryListUp sjckHistoryListUp = sjckHistoryResult.getData();
        // 得到的数据传入插入表的接口中。
        insertTable(sjckHistoryListUp);
        System.out.println("插入到数据库中！");
        // return getPost(HistoryListPath, historyListData, token).getData();
    }

    public void insertTable(SjckHistoryListUp sjckHistoryListUp) throws SQLException {
        // 如果第一天的表不存在，就新建一个表格。
        createDayTable();
        // createTable();
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
        Date date = new Date(System.currentTimeMillis());
        String day = format.format(date);
        String tableName = "history" + day;

        SjckGetHistoryList[] heads = sjckHistoryListUp.getHeads(); // 详情 (signalName,id,unit)
        String[][] values = sjckHistoryListUp.getValues(); // 温度和时间（value,time）

        // 将得到的数据插入到数据表中.
        Connection connection = getConnect();

        PreparedStatement ps = null;
        assert connection != null;
        ps = connection.prepareStatement("insert into "+tableName+
                "(equipId,signalId,signalName,dataType,acquisitionTime,value) values(19146,?,?,?,?,?)");
        for (int i = 0; i < values.length; i ++) {
            for (int j = 1; j < values[0].length; j++) {
                ps.setInt(1,heads[j - 1].getId());
                ps.setString(2,heads[j - 1].getSignalName());
                ps.setString(3,heads[j - 1].getDataType());
                ps.setString(4,values[i][0]);
                ps.setDouble(5,Double. parseDouble(values[i][j]));
                int tag = ps.executeUpdate();
                if (tag != 1) {
                    break;
                }
            }
        }
    }

    private Connection getConnect() {
        try {
            Class.forName(driverName);
            return DriverManager.getConnection(url,username,password);
        }catch (ClassNotFoundException e) {
            e.printStackTrace();
        }catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public Result getPost(String postURL, org.apache.commons.httpclient.NameValuePair[] data, String token){
        try {
            // String postURL = "http://api.lfemcp.com/token/get";
            PostMethod postMethod = null;
            postMethod = new PostMethod(postURL) ;
            postMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8") ;
            postMethod.setRequestHeader("Accept", "application/json;charset=UTF-8");
            if (token != null) {
                postMethod.setRequestHeader("Authorization","Bearer "+token);
            }


            //参数设置，需要注意的就是里边不能传NULL，要传空字符串
            /*NameValuePair[] data = {
                    new NameValuePair("appKey","cf0c23336d214172acbda45f3e5f9240"),
                    new NameValuePair("appSecret","c5f101a6ab2a4a5e9a94d7d2fc9b6a9c"),
                    new NameValuePair("account","CanfitIoT")
            };*/

            postMethod.setRequestBody(data);

            org.apache.commons.httpclient.HttpClient httpClient = new org.apache.commons.httpclient.HttpClient();
            int response = httpClient.executeMethod(postMethod); // 执行POST方法

            System.out.println("1");
            InputStream stream = postMethod.getResponseBodyAsStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(stream));
            StringBuffer stringBuffer = new StringBuffer();
            String str1 = "";
            while((str1 = br.readLine()) != null) {
                stringBuffer.append(str1);
            }
            String sb = stringBuffer.toString();
            String result = new String(sb.getBytes(StandardCharsets.UTF_8));
            JSONObject jsonObject = JSONObject.parseObject(new String(result));

            System.out.println("2");

            return ResultGenerator.genSuccessResult(jsonObject);
        } catch (Exception e) {
            // logger.info("请求异常"+e.getMessage(),e);
            System.out.println("3");
            return ResultGenerator.genFailResult("EXCEPTION");
        }
    }

    // 创建表语句
    @Async
    @Scheduled(cron = "0 0 0 * * ?")
    public void createTable() throws SQLException {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
        Date date = new Date(System.currentTimeMillis());
        String day = format.format(date);
        String tableName = "history" + day;
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");

        SjckTableList tableList = new SjckTableList();
        tableList.setTableName(tableName); tableList.setEstablishDate(sf.format(date));
        tableListMapper.insert(tableList);

        // 连接数据库。
        Connection connection = getConnect();
        if (connection != null) {
            Statement stat = connection.createStatement();
            String sql = "CREATE TABLE " + tableName + "("
                    + "equipId int(8) NOT NULL,"
                    + "signalId int(8) NOT NULL,"
                    + "signalName varchar(255),"
                    + "dataType varchar(255), "
                    + "acquisitionTime varchar(255) NOT NULL, "
                    + "value decimal(4,1) NOT NULL, "
                    + "PRIMARY KEY (signalId,acquisitionTime)"
                    + ") ENGINE=InnoDB DEFAULT CHARSET=utf8;";
            stat.executeUpdate(sql);
            stat.close();
            connection.close();
        }

    }

    // 项目启动时进行运行，避免这一天的数据表丢失。
    private void createDayTable() throws SQLException {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        String day = format.format(date);
        String tableName = "history" + day;
        // 连接数据库。
        Connection connection = getConnect();

        if (connection != null) {
            ResultSet rs = connection.getMetaData().getTables(null,null,tableName,null);

            if (rs.next()) {
                System.out.println("今天的表存在！");
            }else {
                SjckTableList tableList = new SjckTableList();
                tableList.setTableName(tableName); tableList.setEstablishDate(sf.format(date));
                tableListMapper.insert(tableList);
                Statement stat = connection.createStatement();
                String sql = "CREATE TABLE " + tableName + "("
                        + "equipId int(8) NOT NULL,"
                        + "signalId int(8) NOT NULL,"
                        + "signalName varchar(255),"
                        + "dataType varchar(255), "
                        + "acquisitionTime varchar(255) NOT NULL, "
                        + "value decimal(4,1) NOT NULL, "
                        + "PRIMARY KEY (signalId,acquisitionTime)"
                        + ") ENGINE=InnoDB DEFAULT CHARSET=utf8;";
                System.out.println(sql);
                stat.executeUpdate(sql);
                stat.close();
                connection.close();
            }

        }
    }
}
